package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

import beans.Usuario;
import beans.dao.UsuarioDAO;


public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public LoginServlet() {
        super();
    }
    
    public void init(){
   	 
   }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processaLogin(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processaLogin(request, response);
	}
	
	@SuppressWarnings("unchecked")
	public void processaLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		

		HttpSession session = request.getSession();
		String url = "";
		String pk = request.getParameter("email");
		UsuarioDAO DAO = new UsuarioDAO();
		DAO.beginTransaction();
		Usuario u = DAO.retrieve(pk);
		if(u != null){
			
			String pass = request.getParameter("senha");
			if(pass.equals(u.getSenha()) && u.isAtivo()){
				session.setAttribute("usuario", u);
				String urlRequerida = (String) session.getAttribute("url");
				
				if(urlRequerida != null){
					url = urlRequerida;
					session.removeAttribute("url");
				}else{
					url = "/index.jsp";
				}
			}else if(!u.isAtivo()){
				JOptionPane.showMessageDialog(null,"O login digitado se encontra desativado." );
				url="/login.jsp?user="+u.getEmail();
			}else{
				JOptionPane.showMessageDialog(null,"Senha não confere com o usuario." );
				url="/login.jsp?user="+u.getEmail();
			}
		}else{
			JOptionPane.showMessageDialog(null,"Não existe cadastro com esse email. Cadastre-se." );
			url = "/cadastrousuario.jsp"; 
		}
		DAO.commit();

		response.sendRedirect(request.getContextPath() + url);

		//RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		//dispatcher.forward(request, response);
		
	}

}
